package com.power.bank.controller;


import com.alibaba.fastjson2.JSONObject;
import com.power.bank.common.core.domain.AjaxResult;
import com.power.bank.member.domain.PbMember;
import com.power.bank.member.domain.PbMemberAccount;
import com.power.bank.member.service.IPbMemberAccountService;
import com.power.bank.member.service.IPbMemberService;
import com.power.bank.utils.WeiXinUtils;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {


    @Autowired
    WeiXinUtils weiXinUtils;

    @Autowired
    IPbMemberAccountService pbMemberAccountService;

    @Autowired
    IPbMemberService pbMemberService;
    @RequestMapping
    public AjaxResult login(String code) {
        System.out.println(code);


        AjaxResult ajaxResult = null;
        JSONObject result = weiXinUtils.getOpenId(code);
        System.out.println(result);
        if ("0".equals(result.get("errcode"))) {
            String openId = (String) result.get("openid");
            PbMemberAccount pbMemberAccount = pbMemberAccountService.selectPbMemberAccountByAccount(openId, "4");
            if (pbMemberAccount == null) {
                ajaxResult = AjaxResult.error(403, "当前用户未注册！");
            } else {
                PbMember member = pbMemberService.selectPbMemberById(pbMemberAccount.getMid());
                Map data = new HashMap();
                data.put("mid", member.getId());
                data.put("userName", member.getNickname());
                data.put("logo", member.getLogo());
                String token = Jwts.builder().addClaims(data).toString();
                ajaxResult = AjaxResult.success("等会成功", token);
            }


        } else {
            ajaxResult = AjaxResult.error(403, "当前用户未注册！");
        }


        return AjaxResult.success();
    }
}
